package com.longg.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;

public class BaseController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);
        Class<? extends BaseController> aClass = this.getClass();
        try {
            Method method = aClass.getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this,req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected int getUserId(HttpServletRequest req){
        Map userInfoMap = (Map) req.getSession().getAttribute("userInfoMap");
        int id = (int) userInfoMap.get("id");
        return id;
    }

    protected String getUserName(HttpServletRequest req){
        Map userInfoMap = (Map) req.getSession().getAttribute("userInfoMap");
        return (String) userInfoMap.get("username");
    }
}
